'''
Created on Aug 10, 2011

@author: Andrzej
'''

import sys
from PyQt4 import QtCore, QtGui
from Daq328p import Daq328p
import numpy as np
from MyGui_ui import Ui_Form

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
# Matplotlib Figure object
from matplotlib.figure import Figure

class MplCanvas(FigureCanvas):
    """Class to represent the FigureCanvas widget"""
    def __init__(self):
        # setup Matplotlib Figure and Axis
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        # initialization of the canvas
        FigureCanvas.__init__(self, self.fig)
        # we define the widget as expandable
        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        # notify the system of updated policy
        FigureCanvas.updateGeometry(self)
        
class MplWidget(QtGui.QWidget):
    """Widget defined in Qt Designer"""
    def __init__(self, parent = None):
        # initialization of Qt MainWindow widget
        QtGui.QWidget.__init__(self, parent)
        # set the canvas to the Matplotlib widget
        self.canvas = MplCanvas()
        # create a vertical box layout
        self.vbl = QtGui.QVBoxLayout()
        # add mpl widget to vertical box
        self.vbl.addWidget(self.canvas)
        # set the layout to th vertical box
        self.setLayout(self.vbl)

class MyForm(QtGui.QMainWindow):
    
    time = []
    data = []
    
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        #self.Daq = Daq328p("192.168.1.103")
        self.Daq = Daq328p(14)
        
        self.ctimer = QtCore.QTimer()
        
        QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), self.constant)
        QtCore.QObject.connect(self.ui.pushButton_2,QtCore.SIGNAL("clicked()"), self.StopTimer)
        QtCore.QObject.connect(self.ui.ResetButton,QtCore.SIGNAL("clicked()"), self.ResetBar)
        QtCore.QObject.connect(self.ctimer, QtCore.SIGNAL("timeout()"), self.constantUpdate)
        QtCore.QObject.connect(self.ui.pushButton_4,QtCore.SIGNAL("clicked()"), self.GetA2D)
        QtCore.QObject.connect(self.ui.Cmd,QtCore.SIGNAL("returnPressed()"), self.QueryHardware)
        
        QtCore.QMetaObject.connectSlotsByName(self)
        self.ui.mplwidget.axes.set_title("Testing")
        self.ui.mplwidget.axes.set_xlabel("Time")
        self.ui.mplwidget.axes.set_xlim([0, 100])
        
        
        self.fig = self.ui.mplwidget.figure
        self.ax = self.fig.add_subplot(111)
        
        #self.TempPlot = self.ax.plot(self.time,self.data)
        self.TempPlot = self.ax.plot([])
        self.ui.mplwidget.draw()        
        #self.ui.mplwidget.figure.get_axes().extend([0,10,12])  
    
        
        self.ui.Thermo.setMaxValue(250)
        #self.ui.mplwidget.figure = Figure()
        #self.ui.ax = self.ui.mplwidget.figure.add_subplot(111)
        
    def __del__(self):
        self.Daq.close()

    def QueryHardware(self):
        cmd = self.ui.Cmd.text()
        res = self.Daq.query(cmd, expected_text="cmd>",delay=0.1)
        self.ui.Query.append(res)
        self.ui.Query.update()
        self.ui.Cmd.clear()
    
    def GetA2D(self):
        val = self.Daq.GetADC()
        temp = self.Daq.GetTemperature()
        self.ui.ComList.addItem(str(temp[0][1]))
        
        
    def constant(self):
        """
        Start the constant timer
        """
        self.ctimer.start(60*1000)        
       
    
    def StopTimer(self):
        self.ctimer.stop()
        data = np.array(self.data)
        #print data
        
        
    
    def ResetBar(self):
        self.ui.progressBar.setValue(0)
        self.ui.ComList.clear()
        self.ui.mplwidget.axes.set_xlabel('Time [sec]')
        #file = QtGui.QFileDialog.getOpenFileName()
        
        
        
    def constantUpdate(self):
        """
        slot for constant timer timeout
        """
        val = self.ui.progressBar.value() + 1
        if val > 100:
            val = 0
        self.ui.progressBar.setValue(val)
        
        self.time.append(val)
        #val = self.Daq.GetADC(volt=1)
        val = self.Daq.GetTemperature()
        if val:        
            self.data.append(val[0][1])
                    
            x_max = 55.0
            self.ui.mplwidget.axes.set_xlim([0, x_max])
            self.ui.mplwidget.draw()
            #self.ui.ComList.addItem(str(val[0][1]))
            self.TempPlot = self.ax.plot(self.data)
            
            self.ui.mplwidget.draw()
            
            #self.ui.Thermo.setValue(val[0][1]*100)
            self.ui.Thermo.setValue(val[0][1])
              
        
        
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    myapp.show()
    sys.exit(app.exec_())